package com.spice.im.group;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.util.StringUtils;

import cn.finalteam.galleryfinal.GalleryHelper;
import cn.finalteam.galleryfinal.GalleryImageLoader;
import cn.finalteam.galleryfinal.PhotoCropActivity;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import cn.finalteam.toolsfinal.BitmapUtils;
import cn.finalteam.toolsfinal.DateUtils;
import cn.finalteam.toolsfinal.DeviceUtils;
import cn.finalteam.toolsfinal.FileUtils;
import cn.finalteam.toolsfinal.Logger;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.speed.im.login.EncryptionUtil;
import com.spice.im.ContactFrameActivity;
import com.spice.im.FlippingLoadingDialog;
import com.spice.im.R;
import com.spice.im.SpiceApplication;
import com.spice.im.chat.ChatPullRefListActivity;
import com.spice.im.chat.MessageText;
import com.spice.im.preference.PreferenceActivity;
import com.spice.im.preference.PreferenceActivity.exPhoneCallListener;
import com.spice.im.utils.HeaderLayout;
import com.spice.im.utils.HeaderLayout.HeaderStyle;
import com.spice.im.utils.HeaderLayout.onRightImageButtonClickListener;
import com.stb.isharemessage.BeemApplication;
import com.stb.isharemessage.IConnectionStatusCallback;
import com.stb.isharemessage.service.XmppConnectionAdapter;
import com.stb.isharemessage.service.aidl.IXmppFacade;
//import com.example.android.bitmapfun.util.AsyncTask;
import com.spice.im.utils.AsyncTask;
import com.stb.isharemessage.utils.BeemBroadcastReceiver;
import com.stb.isharemessage.utils.BeemConnectivity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.spice.im.ui.HandyTextView;

public class MucCreateActivity extends Activity implements IConnectionStatusCallback{
	private static ExecutorService LIMITED_TASK_EXECUTOR;
    static {
      LIMITED_TASK_EXECUTOR = (ExecutorService) Executors.newFixedThreadPool(7); 
    }; 
	private static final Intent SERVICE_INTENT = new Intent();
	static {
		SERVICE_INTENT.setComponent(new ComponentName("com.spice.im", "com.stb.isharemessage.BeemService"));
	}
    private static final String TAG = "MucCreateActivity";
    
    private final ServiceConnection mServConn = new BeemServiceConnection();
//    private final BeemBroadcastReceiver mReceiver = new BeemBroadcastReceiver();//原来的网络状态注释掉
    private final OkListener mOkListener = new OkListener();
    
    protected FlippingLoadingDialog mLoadingDialog;
	private HeaderLayout mHeaderLayout;
	
	private EditText roomnaturalname;//群聊名称
	private String str_roomnaturalname;
//	private EditText description;//群组介绍
//	private String str_description;
	
	protected TextView mKinds;
	private String kinds;
	
	
	private String muc_room;//群ID(系统分配)
//	private EditText muc_nick;//我的群昵称
	private String str_muc_nick;
//	private EditText muc_password;//加入群聊密码(非必填项)
//	private String str_muc_password;
	private boolean muc_join = true;//加入群聊
	
	private ImageView mIvUserPhoto;
	private LinearLayout mLayoutSelectPhoto;
	private LinearLayout mLayoutTakePicture;
	private Bitmap mUserPhoto;
	
	private Button ok;
	
	private boolean mBinded = false;
    private IXmppFacade mXmppFacade;
    private Context mContext;
    //网络状态start
	private View mNetErrorView;
	private TextView mConnect_status_info;
	private ImageView mConnect_status_btn;
    private exPhoneCallListener myPhoneCallListener = null;
    private TelephonyManager tm = null;
    //网络状态end
    
    public void onCreate(Bundle savedInstanceState) {
    	requestWindowFeature(Window.FEATURE_NO_TITLE);
    	super.onCreate(savedInstanceState);
    	mContext = this;
        setContentView(R.layout.activity_muccreate);
        
        DisplayMetrics dm = DeviceUtils.getScreenPix(this);
        mScreenWidth = dm.widthPixels;
        mScreenHeight = dm.heightPixels;
        
    	mHeaderLayout = (HeaderLayout) findViewById(R.id.login_header);
//    	mHeaderLayout.init(HeaderStyle.DEFAULT_TITLE);
    	mHeaderLayout.init(HeaderStyle.TITLE_RIGHT_IMAGEBUTTON);
//    	mHeaderLayout.setDefaultTitle("创建群组", null);
    	mHeaderLayout.setTitleRightImageButton("创建群组", null,
    			R.drawable.return2,
    			new OnRightImageButtonClickListener());
        mLoadingDialog = new FlippingLoadingDialog(this, "请求提交中");
        
        
        roomnaturalname = (EditText) this.findViewById(R.id.roomnaturalname);
    	
//        description = (EditText) findViewById(R.id.description);
        
        mKinds = (TextView) findViewById(R.id.kinds);
        mKinds.setOnClickListener(mOkListener);
        
        mIvUserPhoto = (ImageView) findViewById(R.id.reg_photo_iv_userphoto);
		mLayoutSelectPhoto = (LinearLayout) findViewById(R.id.reg_photo_layout_selectphoto);
		mLayoutTakePicture = (LinearLayout) findViewById(R.id.reg_photo_layout_takepicture);
		mLayoutSelectPhoto.setOnClickListener(mOkListener);
		mLayoutTakePicture.setOnClickListener(mOkListener);
//        muc_nick = (EditText) findViewById(R.id.muc_nick);
//        muc_password = (EditText) findViewById(R.id.muc_password);
        ok = (Button) findViewById(R.id.ok);
    	ok.setOnClickListener(mOkListener);
//    	this.registerReceiver(mReceiver, new IntentFilter(BeemBroadcastReceiver.BEEM_CONNECTION_CLOSED));//原来的网络状态注释掉
    	
        //网络状态start
        mNetErrorView = findViewById(R.id.net_status_bar_top);
        mConnect_status_info = (TextView)mNetErrorView.findViewById(R.id.net_status_bar_info_top2);
        mConnect_status_btn = (ImageView)mNetErrorView.findViewById(R.id.net_status_bar_btn);
        mConnect_status_btn.setOnClickListener(mOkListener);
        
	    IntentFilter mFilter = new IntentFilter();
	    mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); // 添加接收网络连接状态改变的Action
	    registerReceiver(mNetWorkReceiver, mFilter);
        /* 添加自己实现的PhoneStateListener */
        myPhoneCallListener = new exPhoneCallListener();
       
       /* 取得电话服务 */
        tm =(TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
       
        /* 注册电话通信Listener */
        tm.listen(myPhoneCallListener,PhoneStateListener.LISTEN_CALL_STATE);
	    //网络状态end
        SpiceApplication.getInstance().addActivity(this);
    	
    }
    protected void showKindsDialog() {
		final String[] items = this.getResources().getStringArray(
				R.array.kinds);
		new AlertDialog.Builder(this)
				.setTitle("选择类别")
				.setSingleChoiceItems(items, 0,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								mKinds.setText(items[which]);
								dialog.dismiss();
							}
						}).create().show();

	}
    @Override
    protected void onResume() {
		super.onResume();
		if (!mBinded){
		    mBinded = getApplicationContext().bindService(SERVICE_INTENT, mServConn, BIND_AUTO_CREATE);	    
		}
    }
    @Override
    protected void onStart() {
		super.onStart();
    }
    /**
     * {@inheritDoc}
     */
    @Override
    protected void onPause() {
		super.onPause();
		
    }
    @Override
    protected void onDestroy() {
		super.onDestroy();
		clearAsyncTask();
//		loadingView.isStop = true;
	    try{//网络状态相关
		    if(mXmppFacade!=null && mXmppFacade.getXmppConnectionAdapter()!=null)
		    	mXmppFacade.getXmppConnectionAdapter().unRegisterConnectionStatusCallback();
	    }catch (RemoteException e) {
	    	e.printStackTrace();
	    }
		if (mBinded) {
			getApplicationContext().unbindService(mServConn);
		    mBinded = false;
		}
		mXmppFacade = null;
		//网络状态start
		unregisterReceiver(mNetWorkReceiver); // 删除广播
		if(tm!=null){
			tm.listen(myPhoneCallListener,PhoneStateListener.LISTEN_NONE);//取消监听即可
			tm = null;
		}
		if(myPhoneCallListener!=null)
			myPhoneCallListener = null;
		//网络状态end
//		this.unregisterReceiver(mReceiver);//原来的网络状态注释掉
		Log.e(TAG, "onDestroy activity");
    }
    
    protected List<AsyncTask<Void, Void, Boolean>> mAsyncTasks = new ArrayList<AsyncTask<Void, Void, Boolean>>();
	protected void putAsyncTask(AsyncTask<Void, Void, Boolean> asyncTask) {
		mAsyncTasks.add(asyncTask.executeOnExecutor(LIMITED_TASK_EXECUTOR, null));
	}

	protected void clearAsyncTask() {
		Iterator<AsyncTask<Void, Void, Boolean>> iterator = mAsyncTasks
				.iterator();
		while (iterator.hasNext()) {
			AsyncTask<Void, Void, Boolean> asyncTask = iterator.next();
			if (asyncTask != null && !asyncTask.isCancelled()) {
				asyncTask.cancel(true);
			}
		}
		mAsyncTasks.clear();
	}		    
	protected void showLoadingDialog(String text) {
		if (text != null) {
			mLoadingDialog.setText(text);
		}
		mLoadingDialog.show();
	}

	protected void dismissLoadingDialog() {
		if (mLoadingDialog.isShowing()) {
			mLoadingDialog.dismiss();
		}
	}

	/** 显示自定义Toast提示(来自String) **/
	protected void showCustomToast(String text) {
		View toastRoot = LayoutInflater.from(MucCreateActivity.this).inflate(
				R.layout.common_toast, null);
		((HandyTextView) toastRoot.findViewById(R.id.toast_text)).setText(text);
		Toast toast = new Toast(MucCreateActivity.this);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.setDuration(Toast.LENGTH_SHORT);
		toast.setView(toastRoot);
		toast.show();
	}
	private class OnRightImageButtonClickListener implements
	onRightImageButtonClickListener {
	
		@Override
		public void onClick() {
			startActivity(new Intent(MucCreateActivity.this, ContactFrameActivity.class));//ContactListPullRefListActivity
			MucCreateActivity.this.finish();
		}
	}
	String CurrentUid = "";
    /**
     * The service connection used to connect to the Beem service.
     */
    private class BeemServiceConnection implements ServiceConnection {
		/**
		 * Constructor.
		 */
		public BeemServiceConnection() {
		}
	
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
		    mXmppFacade = IXmppFacade.Stub.asInterface(service);
		    if(mXmppFacade!=null){
		    	mBinded = true;//20130804 added by allen
		    	try{
		    		mXmppFacade.getXmppConnectionAdapter().registerConnectionStatusCallback(MucCreateActivity.this);//网络状态相关
		    		CurrentUid = StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID());
		    	}catch(Exception e){}
		    }
		}
		@Override
		public void onServiceDisconnected(ComponentName name) {
			 try{//网络状态相关
				    if(mXmppFacade!=null && mXmppFacade.getXmppConnectionAdapter()!=null)
				    	mXmppFacade.getXmppConnectionAdapter().unRegisterConnectionStatusCallback();
			    }catch (RemoteException e) {
			    	e.printStackTrace();
			    }
		    mXmppFacade = null;
		    mBinded = false;
		}
    }
    
	public void setUserPhoto(Bitmap bitmap) {
		if (bitmap != null) {
			mUserPhoto = bitmap;
			mIvUserPhoto.setImageBitmap(mUserPhoto);
			return;
		}
		showCustomToast("未获取到图片");
		mUserPhoto = null;
		mIvUserPhoto.setImageResource(R.drawable.ic_common_def_header);
	}
    
    /**
     * Listener.
     */
    private class OkListener implements OnClickListener {
	
		/**
		 * Constructor.
		 */
		public OkListener() { }
	
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
				//网络设置
		        case R.id.net_status_bar_btn:
					setNetworkMethod(mContext);
				break;
				case R.id.reg_photo_layout_selectphoto:
					GalleryHelper.openGallerySingle(MucCreateActivity.this, true, new GalleryImageLoader());
					break;
	
				case R.id.reg_photo_layout_takepicture:
					takePhotoAction();
				break;
				case R.id.kinds:
					showKindsDialog();
					break;
				case R.id.ok:
					str_roomnaturalname = roomnaturalname.getText().toString();
					if (str_roomnaturalname == null || str_roomnaturalname.length()==0) {
						showCustomToast("群聊名称不能为空!");
						return;
					}
//					str_description = description.getText().toString();
//					if (str_description == null || str_description.length()==0) {
//						showCustomToast("群聊介绍不能为空!");
//						return;
//					}
					kinds = mKinds.getText().toString();
					int slashIndex = kinds.indexOf("-");
					String photo_temp = "";
					if(transformfilepath.startsWith("http://")){
						photo_temp = transformfilepath.substring(XmppConnectionAdapter.downloadPrefix.length());
					}else{
						photo_temp = transformfilepath;
					}
					
					if(slashIndex!=-1)
//						startCreate(str_roomnaturalname,transformfilepath,kinds.substring(0, slashIndex));
					startCreate(str_roomnaturalname,photo_temp,kinds.substring(0, slashIndex));
					else//1-自由联盟   默认值
//						startCreate(str_roomnaturalname,transformfilepath,"1");
					startCreate(str_roomnaturalname,photo_temp,"1");
//					upload(transformfilepath,"9999");
				break;
			}
	
		}
    };
	private String[] errorMsg = new String[]{"群聊创建成功.",
			"服务连接中1-1,请稍候再试.",
			"服务连接中1-2,请稍候再试.",
			"服务连接中1-3,请稍候再试.",
			"网络连接不可用,请检查你的网络设置.",
			"系统错误.群聊创建失败.",
			"用户已经加入了该群组，不能重复创建.",//0003
			"创建群组失败,hash校验失败"//0002
			};
	private int errorType = 5;
    private void initCreate(String key,String pic,String fieldid){
		try{
			if(BeemConnectivity.isConnected(getApplicationContext())){
		    if(mXmppFacade!=null 
					&& mXmppFacade.getXmppConnectionAdapter()!=null 
					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee()!=null//&& !mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isConnected()
					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAlive()
					){
		    	    MucCreateIQ reqXML = new MucCreateIQ();
		            reqXML.setId("1234567890");
		            reqXML.setApikey("abcdefghijklmnopqrstuvwxyz");
		            reqXML.setUid(StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID()));//2
		            SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
		    	    String username = settings.getString(BeemApplication.ACCOUNT_USERNAME_KEY, "");
		            reqXML.setUsername(username);
		            reqXML.setKey(key);
		            reqXML.setPic(pic);
		            reqXML.setFieldid(fieldid);
		            String uuid = mXmppFacade.getXmppConnectionAdapter().getAdaptee().getUUID(this,username);
		            reqXML.setUuid(uuid);
		            reqXML.setIds("");
	//	            String hashcode = "";//apikey+view+orderby+uuid 使用登录成功后返回的sessionid作为密码做3des运算
//		            String hash_dest_src = "abcdefghijklmnopqrstuvwxyz"+ StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID())+uuid+key;
		            String hash_dest_src = "abcdefghijklmnopqrstuvwxyz"+ StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID())+uuid;//去掉key，避免中文编码问题导致平台测校验sha不通过
		            String hash_dest = EncryptionUtil.getHash2(hash_dest_src, "SHA");
		            reqXML.setHashcode(hash_dest);
		            reqXML.setType(IQ.Type.SET);
		            String elementName = "muccreateiq"; 
		    		String namespace = "com:isharemessage:muccreateiq";
		    		MucCreateIQResponseProvider provider = new MucCreateIQResponseProvider();
		            Packet rt =  mXmppFacade.getXmppConnectionAdapter().excute(reqXML, "muccreateiq", "com:isharemessage:muccreateiq", provider);
		            
		            if(rt!=null){
		                if (rt instanceof MucCreateIQResponse) {
		                	final MucCreateIQResponse mucCreateIQResponse = (MucCreateIQResponse) rt;
	
		                    if (mucCreateIQResponse.getChildElementXML().contains(
		                            "com:isharemessage:muccreateiq")) {
	//	    					MainActivity.this.runOnUiThread(new Runnable() {
	//		                    	
	//    							@Override
	//    							public void run() {
	//    								showCustomToast("服务器应答消息："+contactGroupListIQResponse.toXML().toString());
	//    							}
	//    						});
		                        String Id = mucCreateIQResponse.getId();
		                        String Apikey = mucCreateIQResponse.getApikey();
		                        String retcode = mucCreateIQResponse.getRetcode();
		                        String memo = mucCreateIQResponse.getMemo();
		                        if(retcode.equalsIgnoreCase("0000"))
		                        	errorType = 0;
		                        else if(retcode.equalsIgnoreCase("0003"))
		                        	errorType = 6;
		                        else if(retcode.equalsIgnoreCase("0002"))
		                        	errorType = 7;
		                        else
		                        	errorType = 5;
		                        return;
		                    }
		                } 
		            }
		    		errorType = 1;

		    }else
		    	errorType = 1;
		    
			}else
				errorType = 4;
		}catch(RemoteException e){
			e.printStackTrace();
			errorType = 2;
		}catch(Exception e){
			e.printStackTrace();
			errorType = 3;
		}
    }
	private void startCreate(final String key,final String pic,final String fieldid) {

		putAsyncTask(new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				showLoadingDialog("正在加载,请稍后...");
			}

			@Override
			protected Boolean doInBackground(Void... params) {
//				initContactList();
				initCreate(key,pic,fieldid);
				return true;
			}

			@Override
			protected void onPostExecute(Boolean result) {
				super.onPostExecute(result);
				dismissLoadingDialog();
				if (!result) {
					showCustomToast("数据加载失败...");
					mHandler.sendEmptyMessage(3);
				} else {
					mHandler.sendEmptyMessage(0);
				}
//				ptrstgv.getRefreshableView().hideFooterView();
			}

		});
	}
	Handler mHandler = new Handler() {

		@Override
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 0:
				if(errorType!=0)
					showCustomToast(errorMsg[errorType]);
				else{
					showCustomToast("群聊创建成功!");
					startActivity(new Intent(MucCreateActivity.this, ContactFrameActivity.class));//ContactListPullRefListActivity
					MucCreateActivity.this.finish();
				}
				break;

			case 1:
				
				progress.setText(msg.arg1+"%");//20150831 第三种方法
				bar.setProgress(msg.arg1);//20150831 第三种方法
				break;
			case 2:
				progress.setText("100%");//20150831 第三种方法
				bar.setProgress(100);//20150831 第三种方法
				
				creatingProgress.dismiss();
//				transformfilepath = 
				if(transformfilepath.lastIndexOf("/")!=-1){
//					transformfilepath = XmppConnectionAdapter.downloadPrefix+"/9999"+"/"+transformfilepath.substring(transformfilepath.lastIndexOf("/")+1);
					transformfilepath = XmppConnectionAdapter.downloadPrefix+"/userfiles/"+CurrentUid+"/images/photo/"+transformfilepath.substring(transformfilepath.lastIndexOf("/")+1);
				}else{
//					transformfilepath = XmppConnectionAdapter.downloadPrefix+"/9999"+"/"+transformfilepath;
					transformfilepath = XmppConnectionAdapter.downloadPrefix+"/userfiles/"+CurrentUid+"/images/photo/"+transformfilepath;
				}
			    break;
			case 3:
				progress.setText("上传失败!");
				creatingProgress.dismiss();
				break;
			case 4:
				initialProgressDialog();
				creatingProgress.show();
				break;
			default:
				if(errorType!=5)
					showCustomToast(errorMsg[errorType]);
				break;
			}
		}

	};
	
	
	Uri uri = null;
	//利用requestCode区别开不同的返回结果
	//resultCode参数对应于子模块中setResut(int resultCode, Intent intent)函数中的resultCode值，用于区别不同的返回结果（如请求正常、请求异常等）
	//对应流程：
	//母模块startActivityForResult--触发子模块，根据不同执行结果设定resucode值，最后执行setResut并返回到木模块--母模块触发onActivityResult，根据requestcode参数区分不同子模块。
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==2 && resultCode==2 && data!=null){
        	String filepath = data.getStringExtra("filepath");
        	Toast.makeText(MucCreateActivity.this, "filepath="+filepath, Toast.LENGTH_LONG).show();
			if(filepath.length() > 0){
//				sendFile(filepath);//P2P send file
				File file = new File(filepath);
				if (file.exists() && file.canRead()) {
					sendOfflineFile(filepath,"file");//send offline file via agent file server 
								    
				} else {
					Toast.makeText(MucCreateActivity.this, "file not exists", Toast.LENGTH_LONG).show();
				}
			}
        }
        else if ( requestCode == GalleryHelper.GALLERY_REQUEST_CODE) {
            if ( resultCode == GalleryHelper.GALLERY_RESULT_SUCCESS ) {
                PhotoInfo photoInfo = data.getParcelableExtra(GalleryHelper.RESULT_DATA);
                List<PhotoInfo> photoInfoList = (List<PhotoInfo>) data.getSerializableExtra(GalleryHelper.RESULT_LIST_DATA);

                if ( photoInfo != null ) {
//                    ImageLoader.getInstance().displayImage("file:/" + photoInfo.getPhotoPath(), mIvResult);
                    uri = Uri.parse("file:/" + photoInfo.getPhotoPath());
                    Toast.makeText(this, "选择了照片路径:" + photoInfo.getPhotoPath(), Toast.LENGTH_SHORT).show();
                    sendOfflineFile(photoInfo.getPhotoPath(),"img");
                }

                if ( photoInfoList != null ) {
                    Toast.makeText(this, "选择了" + photoInfoList.size() + "张", Toast.LENGTH_SHORT).show();
                }
            }
        }
        else if ( requestCode == GalleryHelper.TAKE_REQUEST_CODE ) {
            if (resultCode == RESULT_OK && mTakePhotoUri != null) {
                final String path = mTakePhotoUri.getPath();
                final PhotoInfo info = new PhotoInfo();
                info.setPhotoPath(path);
//                updateGallery(path);

                final int degress = BitmapUtils.getDegress(path);
                if (degress != 0) {
                    new AsyncTask<Void, Void, Void>() {

                        @Override
                        protected void onPreExecute() {
                            super.onPreExecute();
                            toast("请稍等…");
                        }

                        @Override
                        protected Void doInBackground(Void... params) {
                            try {
                                Bitmap bitmap = rotateBitmap(path, degress);
                                saveRotateBitmap(bitmap, path);
                                bitmap.recycle();
                            } catch (Exception e) {
                                Logger.e(e);
                            }
                            return null;
                        }

                        @Override
                        protected void onPostExecute(Void voids) {
                            super.onPostExecute(voids);
//                            takeResult(info);
                            toPhotoCrop(info);
                        }
                    }.execute();
                } else {
//                    takeResult(info);
                	toPhotoCrop(info);
                }
            } else {
                toast("拍照失败");
            }
        } else if ( requestCode == GalleryHelper.CROP_REQUEST_CODE) {
            if ( resultCode == GalleryHelper.CROP_SUCCESS ) {
                PhotoInfo photoInfo = data.getParcelableExtra(GalleryHelper.RESULT_DATA);
                resultSingle(photoInfo);
            }
        } else if ( requestCode == GalleryHelper.GALLERY_RESULT_SUCCESS ) {
            PhotoInfo photoInfo = data.getParcelableExtra(GalleryHelper.RESULT_DATA);
            List<PhotoInfo> photoInfoList = (List<PhotoInfo>) data.getSerializableExtra(GalleryHelper.RESULT_LIST_DATA);

            if ( photoInfo != null ) {
//                ImageLoader.getInstance().displayImage("file:/" + photoInfo.getPhotoPath(), mIvResult);
                uri = Uri.parse("file:/" + photoInfo.getPhotoPath());
                Toast.makeText(this, "选择了照片路径:" + photoInfo.getPhotoPath(), Toast.LENGTH_SHORT).show();
                sendOfflineFile(photoInfo.getPhotoPath(),"img");
            }

            if ( photoInfoList != null ) {
                Toast.makeText(this, "选择了" + photoInfoList.size() + "张", Toast.LENGTH_SHORT).show();
            }
        }
    }
    
    //recodeTime
    String transformfilepath = "";
    String transformfiletype = "";
    private void sendOfflineFile(String filepath,String type) {
		
    	transformfilepath = filepath;
    	transformfiletype = type;
    	
		try{
    		File file2 = new File(transformfilepath);
    		if(file2.exists()){
    			Bitmap bitmap = BitmapFactory.decodeFile(transformfilepath);
    			setUserPhoto(bitmap);
    			upload(transformfilepath,"9999");
    			
    		}
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}
    
    
    /**
     * 拍照
     */
    String mPhotoTargetFolder = null;
    Uri mTakePhotoUri = null;
    protected void takePhotoAction() {

        if (!DeviceUtils.existSDCard()) {
//            toast("没有SD卡不能拍照呢~");
        	Toast.makeText(this, "没有SD卡不能拍照呢~", Toast.LENGTH_SHORT).show();
            return;
        }

        File takePhotoFolder = null;
        if (cn.finalteam.toolsfinal.StringUtils.isEmpty(mPhotoTargetFolder)) {
            takePhotoFolder = new File(Environment.getExternalStorageDirectory(),
                    "/DCIM/" + GalleryHelper.TAKE_PHOTO_FOLDER);
        } else {
            takePhotoFolder = new File(mPhotoTargetFolder);
        }

        File toFile = new File(takePhotoFolder, "IMG" + DateUtils.format(new Date(), "yyyyMMddHHmmss") + ".jpg");
        boolean suc = FileUtils.makeFolders(toFile);
        Logger.d("create folder=" + toFile.getAbsolutePath());
        if (suc) {
            mTakePhotoUri = Uri.fromFile(toFile);
            Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mTakePhotoUri);
            startActivityForResult(captureIntent, GalleryHelper.TAKE_REQUEST_CODE);
        }
    }
    protected int mScreenWidth = 720;
    protected int mScreenHeight = 1280;
    protected Bitmap rotateBitmap(String path, int degress) {
        try {
            Bitmap bitmap = BitmapUtils.compressBitmap(path, mScreenWidth / 4, mScreenHeight / 4);
            bitmap = BitmapUtils.rotateBitmap(bitmap, degress);
            return bitmap;
        } catch (Exception e) {
            Logger.e(e);
        }

        return null;
    }

    protected void saveRotateBitmap(Bitmap bitmap, String path) {
        //保存
        BitmapUtils.saveBitmap(bitmap, new File(path));
        //修改数据库
        ContentValues cv = new ContentValues();
        cv.put("orientation", 0);
        ContentResolver cr = getContentResolver();
        String where = new String(MediaStore.Images.Media.DATA + "='" + cn.finalteam.toolsfinal.StringUtils.sqliteEscape(path) +"'");
        cr.update(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, cv, where, null);
    }
    public void toast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }
    protected void resultSingle(PhotoInfo photoInfo) {
//        Intent intent = getIntent();
//        if (intent == null) {
//            intent = new Intent();
//        }
//        intent.putExtra(GalleryHelper.RESULT_DATA, photoInfo);
////        setResult(GalleryHelper.GALLERY_RESULT_SUCCESS, intent);
////        finish();
//        startActivityForResult(intent, GalleryHelper.GALLERY_RESULT_SUCCESS);
    	
        if ( photoInfo != null ) {
//          ImageLoader.getInstance().displayImage("file:/" + photoInfo.getPhotoPath(), mIvResult);
          uri = Uri.parse("file:/" + photoInfo.getPhotoPath());
          Toast.makeText(this, "选择了照片路径:" + photoInfo.getPhotoPath(), Toast.LENGTH_SHORT).show();
          sendOfflineFile(photoInfo.getPhotoPath(),"img");
      }
    }
    /**
     * 执行裁剪
     */
    protected void toPhotoCrop(PhotoInfo info) {
        Intent intent = new Intent(this, PhotoCropActivity.class);
        intent.putExtra(PhotoCropActivity.PHOTO_INFO, info);
        startActivityForResult(intent, GalleryHelper.CROP_REQUEST_CODE);
    }
    
    
    public void upload(String mPicPath,String fromAccount){
    	try{
            final File file = new File(mPicPath);  
            
            if (file != null) {  
//                String request = UploadUtil.uploadFile(file, requestURL);  
//                String uploadHost="http://10.0.2.2:9090/plugins/offlinefiletransfer/offlinefiletransfer";  
            	String uploadHost = XmppConnectionAdapter.uploadHost.replace("OfflinefiletransferServlet", "UploadHeadServlet");
            	uploadHost = XmppConnectionAdapter.downloadPrefix+"/maps/Resource/uploadFeed.jsp";
            	//                RequestParams params=new RequestParams();  
////                params.addBodyParameter("msg",imgtxt.getText().toString());   
//                params.addBodyParameter(picPath.replace("/", ""), file);   
//                uploadMethod(params,uploadHost);
////                uploadImage.setText(request);  
                RequestParams params = new RequestParams();
//                params.addHeader("name", "value");
//                params.addHeader(HttpUtils.HEADER_ACCEPT_ENCODING, HttpUtils.ENCODING_GZIP);
                params.addHeader("Accept-Encoding", "gzip");
//                params.addQueryStringParameter("name", "value");
                params.addQueryStringParameter("fromAccount", CurrentUid);//代表存储目录
//                SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
//        	    String uid = settings.getString("uidStr", "");
        	    params.addQueryStringParameter("uidStr", CurrentUid);
                params.addQueryStringParameter("sendType", "img");
                params.addQueryStringParameter("sendSize", "0");
                // 只包含字符串参数时默认使用BodyParamsEntity，
                // 类似于UrlEncodedFormEntity（"application/x-www-form-urlencoded"）。
//                params.addBodyParameter("fromAccount", fromAccount);
//                params.addBodyParameter("toAccount", toAccount);
//                params.addBodyParameter("sendType", "audio");
//                params.addBodyParameter("sendSize", (int) mRecord_Time+"");

                // 加入文件参数后默认使用MultipartEntity（"multipart/form-data"），
                // 如需"multipart/related"，xUtils中提供的MultipartEntity支持设置subType为"related"。
                // 使用params.setBodyEntity(httpEntity)可设置更多类型的HttpEntity（如：
                // MultipartEntity,BodyParamsEntity,FileUploadEntity,InputStreamUploadEntity,StringEntity）。
                // 例如发送json参数：params.setBodyEntity(new StringEntity(jsonStr,charset));
//                BodyParamsEntity bpe = new BodyParamsEntity();
//                bpe.addParameter("fromAccount", fromAccount);
//                bpe.addParameter("toAccount", toAccount);
//                bpe.addParameter("sendType", "audio");
//                bpe.addParameter("sendSize", (int) mRecord_Time+"");
//                params.setBodyEntity(bpe);
                params.addBodyParameter("file", file);
                uploadMethod(params,uploadHost);
                
            }  
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    }
    
	private HttpUtils http;
	private HttpHandler handler;
	
    //上传照片start
    public  void uploadMethod(final RequestParams params,final String uploadHost) {  
    	http = new HttpUtils();
    	http.configCurrentHttpCacheExpiry(1000 * 10); // 设置缓存10秒，10秒内直接返回上次成功请求的结果。
    	
    	handler = http.send(HttpRequest.HttpMethod.POST, uploadHost, params,new RequestCallBack<String>() {  
                    @Override  
                    public void onStart() {  
//                      msgTextview.setText("conn...");  
                      mHandler.sendEmptyMessage(4);
                    }  
                    @Override  
                    public void onLoading(long total, long current,boolean isUploading) {  
//                        if (isUploading) {  
//                          msgTextview.setText("upload: " + current + "/"+ total);  
//                        } else {  
//                          msgTextview.setText("reply: " + current + "/"+ total);  
//                        }  
    					android.os.Message message = mHandler.obtainMessage();
//    					message.arg1 = (int) (current*100/total);
    					message.arg1 = 80;//gzip 后 total为0
    					message.what = 1;
    		//								message.sendToTarget();
    					mHandler.sendMessage(message);
                    }  
                    public void onSuccess(ResponseInfo<String> responseInfo) { 
                    	Log.e("※※※※※####20140806####※※※※※", "※※上传成功"+responseInfo.statusCode+";reply: " + responseInfo.result);
                    	//statuscode == 200
//                      msgTextview.setText("statuscode:"+responseInfo.statusCode+";reply: " + responseInfo.result); 
                    	
                    	mHandler.sendEmptyMessage(2);
                    }  
                    public void onFailure(HttpException error, String msg) {  
//                      msgTextview.setText(error.getExceptionCode() + ":" + msg);  
                    	Log.e("※※※※※####20140806####※※※※※", "※※上传失败"+error.getExceptionCode() + ":" + msg);
                    	mHandler.sendEmptyMessage(3);
                    }  
                });  
        
    } 
    //上传照片end
    
    private  Dialog creatingProgress = null;
	private ProgressBar bar;
	private TextView progress;
	
	public void initialProgressDialog(){
		//创建处理进度条
		creatingProgress= new Dialog(MucCreateActivity.this,R.style.Dialog_loading_noDim);
		Window dialogWindow = creatingProgress.getWindow();
		WindowManager.LayoutParams lp = dialogWindow.getAttributes();
		lp.width = (int) (getResources().getDisplayMetrics().density*240);
		lp.height = (int) (getResources().getDisplayMetrics().density*80);
		lp.gravity = Gravity.CENTER;
		dialogWindow.setAttributes(lp);
		creatingProgress.setCanceledOnTouchOutside(false);//禁用取消按钮
		creatingProgress.setContentView(R.layout.activity_recorder_progress);
		
		progress = (TextView) creatingProgress.findViewById(R.id.recorder_progress_progresstext);
		bar = (ProgressBar) creatingProgress.findViewById(R.id.recorder_progress_progressbar);
	}
	//网络状态 start
		@Override
		public void connectionStatusChanged(int connectedState, String reason) {
			Log.e("MMMMM20140604MMMMMMMMMMMM", "++++++++++++++connectionStatusChanged0++++++++++++");
			switch (connectedState) {
			case 0://connectionClosed
				mHandler3.sendEmptyMessage(0);
				break;
			case 1://connectionClosedOnError
//				mConnectErrorView.setVisibility(View.VISIBLE);
//				mNetErrorView.setVisibility(View.VISIBLE);
//				mConnect_status_info.setText("连接异常!");
				mHandler3.sendEmptyMessage(1);
				break;
			case 2://reconnectingIn
//				mNetErrorView.setVisibility(View.VISIBLE);
//				mConnect_status_info.setText("连接中...");
				mHandler3.sendEmptyMessage(2);
				break;
			case 3://reconnectionFailed
//				mNetErrorView.setVisibility(View.VISIBLE);
//				mConnect_status_info.setText("重连失败!");
				mHandler3.sendEmptyMessage(3);
				break;
			case 4://reconnectionSuccessful
//				mNetErrorView.setVisibility(View.GONE);
				mHandler3.sendEmptyMessage(4);

			default:
				break;
			}
		}
		Handler mHandler3 = new Handler() {

			@Override
			public void handleMessage(android.os.Message msg) {
				super.handleMessage(msg);
				switch (msg.what) {
				case 0:
					break;

				case 1:
					mNetErrorView.setVisibility(View.VISIBLE);
					if(BeemConnectivity.isConnected(mContext))
					mConnect_status_info.setText("连接异常!");
					break;

				case 2:
					mNetErrorView.setVisibility(View.VISIBLE);
					if(BeemConnectivity.isConnected(mContext))
					mConnect_status_info.setText("连接中...");
					break;
				case 3:
					mNetErrorView.setVisibility(View.VISIBLE);
					if(BeemConnectivity.isConnected(mContext))
					mConnect_status_info.setText("重连失败!");
					break;
					
				case 4:
					mNetErrorView.setVisibility(View.GONE);
					String udid = "";
					String partnerid = "";
					try{
						udid = mXmppFacade.getXmppConnectionAdapter().getAdaptee().UDID;
						partnerid = mXmppFacade.getXmppConnectionAdapter().getMService().getPartnerid();
					}catch(Exception e){
						e.printStackTrace();
					}
//					udidTextView.setText("udid="+udid);
//					partneridEditText.setText(partnerid);
//					getContactList();//20141025 added by allen
					break;
				case 5:
					mNetErrorView.setVisibility(View.VISIBLE);
					mConnect_status_info.setText("当前网络不可用，请检查你的网络设置。");
					break;
				case 6:
					if(mXmppFacade!=null 
//							&& mXmppFacade.getXmppConnectionAdapter()!=null 
//							&& mXmppFacade.getXmppConnectionAdapter().getAdaptee()!=null//&& !mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
//							&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isConnected()
//							&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
							&& BeemConnectivity.isConnected(mContext)){
						
					}else{
						mNetErrorView.setVisibility(View.VISIBLE);
						if(BeemConnectivity.isConnected(mContext))
						mConnect_status_info.setText("网络可用,连接中...");
					}
					break;	
				}
			}

		};
		private BroadcastReceiver mNetWorkReceiver = new BroadcastReceiver() {
	        @Override
	        public void onReceive(Context context, Intent intent) {
	            String action = intent.getAction();  
	            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {  
	                Log.d("PoupWindowContactList", "网络状态已经改变");  
//	                connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);  
//	                info = connectivityManager.getActiveNetworkInfo();    
//	                if(info != null && info.isAvailable()) {  
//	                    String name = info.getTypeName();  
//	                    Log.d(tag, "当前网络名称：" + name);  
//	                    //doSomething()  
//	                } else {  
//	                    Log.d(tag, "没有可用网络");  
//	                  //doSomething()  
//	                }  
	                if(BeemConnectivity.isConnected(context)){
//	                	mNetErrorView.setVisibility(View.GONE);
//	                	isconnect = 0;
	                	mHandler3.sendEmptyMessage(6);//4
	                }else{
//	                	mNetErrorView.setVisibility(View.VISIBLE);
//	                	isconnect = 1;
	                	mHandler3.sendEmptyMessage(5);
	                	Log.d("PoupWindowContactList", "当前网络不可用，请检查你的网络设置。");
	                }
	            } 
	        }
		};
		
		private boolean phonestate = false;//false其他， true接起电话或电话进行时 
	    /* 内部class继承PhoneStateListener */
	    public class exPhoneCallListener extends PhoneStateListener
	    {
	        /* 重写onCallStateChanged
	        当状态改变时改变myTextView1的文字及颜色 */
	        public void onCallStateChanged(int state, String incomingNumber)
	        {
	          switch (state)
	          {
	            /* 无任何状态时 :说明没有拨打电话的界面的时候，也就是在拨打电话前和挂电话后的情况*/
	            case TelephonyManager.CALL_STATE_IDLE:
	            	Log.e("================20131216 无任何电话状态时================", "无任何电话状态时");
	            	if(phonestate){
	            		onPhoneStateResume();
	            	}
	            	phonestate = false;
	              break;
	            /* 接起电话时 :至少有一个电话存在、拨出或激活、接听，而没有一个电话在通话或等待的状态*/
	            case TelephonyManager.CALL_STATE_OFFHOOK:
	            	Log.e("================20131216 接起电话时================", "接起电话时");
	            	onPhoneStatePause();
	            	phonestate = true;
	              break;
	            /* 电话进来时 :在通话的过程中*/
	            case TelephonyManager.CALL_STATE_RINGING:
//	              getContactPeople(incomingNumber);
	            	Log.e("================20131216 电话进来时================", "电话进来时");
//	            	onBackPressed();
	            	onPhoneStatePause();
	            	phonestate = true;
	              break;
	            default:
	              break;
	          }
	          super.onCallStateChanged(state, incomingNumber);
	        }
	    }
	    
	    protected void onPhoneStatePause() {
//			super.onPause();
	    	try{
//	    		try {
//	    		    if (mRoster != null) {
//	    			mRoster.removeRosterListener(mBeemRosterListener);
//	    			mRoster = null;
//	    		    }
//	    		} catch (RemoteException e) {
//	    		    Log.d("ContactList", "Remote exception", e);
//	    		}
				if (mBinded) {
					getApplicationContext().unbindService(mServConn);
				    mBinded = false;
				}
				mXmppFacade = null;
	    	}catch(Exception e){
	    		e.printStackTrace();
	    	}
	    }
	    
	    protected void onPhoneStateResume() {
//			super.onResume();
	    	try{
			if (!mBinded){
//			    new Thread()
//			    {
//			        @Override
//			        public void run()
//			        {
			    mBinded = getApplicationContext().bindService(SERVICE_INTENT, mServConn, BIND_AUTO_CREATE);

//			        }
//			    }.start();		    
			}
			if (mBinded){
//				mImageFetcher.setExitTasksEarly(false);
			}
	    	}catch(Exception e){
	    		e.printStackTrace();
	    	}
	    }
	    
	    /*
	     * 打开设置网络界面
	     * */
	    public static void setNetworkMethod(final Context context){
	        //提示对话框
	        AlertDialog.Builder builder=new AlertDialog.Builder(context);
	        builder.setTitle("网络设置提示").setMessage("网络连接不可用,是否进行设置?").setPositiveButton("设置", new DialogInterface.OnClickListener() {
	            
	            @Override
	            public void onClick(DialogInterface dialog, int which) {
	                // TODO Auto-generated method stub
	                Intent intent=null;
	                //判断手机系统的版本  即API大于10 就是3.0或以上版本 
	                if(android.os.Build.VERSION.SDK_INT>10){
	                    intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
	                }else{
	                    intent = new Intent();
	                    ComponentName component = new ComponentName("com.android.settings","com.android.settings.WirelessSettings");
	                    intent.setComponent(component);
	                    intent.setAction("android.intent.action.VIEW");
	                }
	                context.startActivity(intent);
	            }
	        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
	            
	            @Override
	            public void onClick(DialogInterface dialog, int which) {
	                // TODO Auto-generated method stub
	                dialog.dismiss();
	            }
	        }).show();
	    }
		//网络状态 end
}
